package com.easy.controller;

import com.easy.service.PasswordResetService;
import com.easy.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/api/password")
public class PasswordResetController {

    @Autowired
    private PasswordResetService passwordResetService;

    @PostMapping("/send-code")
    public Result sendVerificationCode(@RequestBody Map<String, String> request) {
        try {
            String email = request.get("email");
            if (email == null || email.isEmpty()) {
                return Result.fail(500, "邮箱地址不能为空");
            }

            passwordResetService.sendVerificationCode(email);
            return Result.success("验证码已发送到您的邮箱");
        } catch (Exception e) {
            return Result.fail(500, "发送验证码失败: " + e.getMessage());
        }
    }

    @PostMapping("/verify-code")
    public Result verifyCode(@RequestBody Map<String, String> request) {
        try {
            String email = request.get("email");
            String code = request.get("code");

            if (email == null || email.isEmpty()) {
                return Result.fail(500, "邮箱地址不能为空");
            }
            if (code == null || code.isEmpty()) {
                return Result.fail(500, "验证码不能为空");
            }

            boolean result = passwordResetService.verifyCode(email, code);
            if (result) {
                return Result.success("验证码验证成功");
            } else {
                return Result.fail(500, "验证码错误或已过期");
            }
        } catch (Exception e) {
            return Result.fail(500, "验证验证码失败: " + e.getMessage());
        }
    }

    @PostMapping("/reset")
    public Result resetPassword(@RequestBody Map<String, String> request) {
        try {
            String email = request.get("email");
            String newPassword = request.get("newPassword");

            if (email == null || email.isEmpty()) {
                return Result.fail(500, "邮箱地址不能为空");
            }
            if (newPassword == null || newPassword.isEmpty()) {
                return Result.fail(500, "新密码不能为空");
            }
            if (newPassword.length() < 6) {
                return Result.fail(500, "密码长度不能少于6位");
            }

            boolean result = passwordResetService.resetPassword(email, newPassword);
            if (result) {
                return Result.success("密码重置成功");
            } else {
                return Result.fail(500, "密码重置失败，请先验证邮箱");
            }
        } catch (Exception e) {
            return Result.fail(500, "重置密码失败: " + e.getMessage());
        }
    }
}
